package com.jn.mvvm.views;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.jn.mvvm.R;
import com.jn.mvvm.common.WeakRrfHandler;
import com.jn.mvvm.databinding.ActivityMainBinding;
import com.jn.mvvm.entity.Book;
import com.jn.mvvm.utils.LogUtils;

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        Book book = new Book();
        book.setName("Android从入门到精通");
        book.setAuthor("Kong");
        binding.setBookinfo(book);
        binding.bookIntroduce.setText("wewerwer000");
        mHandler.sendEmptyMessageDelayed(0, 2000);
        binding.button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toSecond();
            }
        });
        binding.setListener(new ButtonClickListener());
    }

    WeakRrfHandler mHandler = new WeakRrfHandler(Looper.getMainLooper(), this, new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            LogUtils.d("asdf", "toString1====" + binding.getBookinfo().toString());
            binding.booknametv.setText("大学计算机基础2");
            binding.bookAuthor.setText("zhangsan");
            LogUtils.d("asdf", "toString2====" + binding.getBookinfo().toString());
            return false;
        }
    });

    private void toSecond(Book... books) {
        Intent intent = new Intent(MainActivity.this, SecondActivity.class);
        if (books != null && books.length > 0) {
            Book book = books[0];
            intent.putExtra("book", book);
        }
        startActivity(intent);
    }

    public class ButtonClickListener {
        public void onClick(View view) {
            int id = view.getId();
            if (id == R.id.button2) {
                toSecond();
            } else if (id == R.id.button3) {
                Toast.makeText(getApplicationContext(), "click 3", Toast.LENGTH_SHORT).show();
            }
        }

        public void onClick(View view, Book book) {
            int id = view.getId();
            if (id == R.id.button4) {
                toSecond(book);
            }
        }
    }
}